//
//  ZMTextView.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/31.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit

class ZMTextView: UITextView {

    //懒加载placeHolderLabel
    fileprivate lazy var placeHolderLabel: UILabel = {
        let label = UILabel(text: "请输入微博内容", fontSize: 14, textColor: UIColor.lightGray)
    
        label.numberOfLines  = 0
        
        return label
    }()
    //设置占位文本,对外接口
    var placeHolder: String?{
        didSet{
            placeHolderLabel.text = placeHolder
        }
    }
    //外部设置文本的字体大小
    override var font: UIFont?{
        didSet{
            if font != nil {
                
                placeHolderLabel.font = font
            }
            
        }
    }
    
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        self.backgroundColor = UIColor.white
        
        //添加placeHolder控件
        addSubview(placeHolderLabel)
        //设置约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        
        //添加通知,监听当前textview中的文字的变化
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged(info:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        
    }
    
    //MARK:- textview中文字编辑发生变化监听事件
    @objc private func textChanged(info: Notification){
        
        placeHolderLabel.isHidden = self.hasText
        
    }
    
    //移除通知监听
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
}
